import os
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO
import uuid
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def allowed_file(filename, allowed_extensions):
    """Check if the file has an allowed extension"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

def generate_meme(template_url, top_text, bottom_text, output_folder):
    """
    Generate a meme by adding text to a template image
    
    Args:
        template_url (str): URL of the template image
        top_text (str): Text to add at the top of the image
        bottom_text (str): Text to add at the bottom of the image
        output_folder (str): Folder to save the generated meme
        
    Returns:
        str: Filename of the generated meme
    """
    try:
        # Download the template image
        response = requests.get(template_url)
        img = Image.open(BytesIO(response.content))
        
        # Get image dimensions
        width, height = img.size
        
        # Create a drawing context
        draw = ImageDraw.Draw(img)
        
        # Try to get the Impact font, fall back to a default if not available
        try:
            font_size = int(height/10)  # Scale font size based on image height
            font = ImageFont.truetype("Impact.ttf", font_size)
        except IOError:
            logger.warning("Impact font not found, using default")
            font = ImageFont.load_default()
        
        # Add top text
        if top_text:
            # Calculate text width and height for centering
            text_width = draw.textlength(top_text, font=font)
            text_x = (width - text_width) / 2
            
            # Draw text with black outline for visibility
            draw_text_with_outline(draw, (text_x, 10), top_text, font)
        
        # Add bottom text
        if bottom_text:
            # Calculate text width and height for centering
            text_width = draw.textlength(bottom_text, font=font)
            text_x = (width - text_width) / 2
            
            # Draw text with black outline for visibility
            draw_text_with_outline(draw, (text_x, height - font_size - 10), bottom_text, font)
        
        # Generate a unique filename
        filename = f"{uuid.uuid4()}.jpg"
        filepath = os.path.join(output_folder, filename)
        
        # Save the image
        img.save(filepath)
        
        return filename
    
    except Exception as e:
        logger.error(f"Error generating meme: {str(e)}")
        return None

def draw_text_with_outline(draw, position, text, font, outline_width=2):
    """
    Draw text with an outline for better visibility on varying backgrounds
    
    Args:
        draw: ImageDraw object
        position (tuple): (x, y) position to draw text
        text (str): Text to draw
        font: Font to use
        outline_width (int): Width of the outline
    """
    x, y = position
    
    # Draw black outline
    for offset_x in range(-outline_width, outline_width + 1):
        for offset_y in range(-outline_width, outline_width + 1):
            draw.text((x + offset_x, y + offset_y), text, font=font, fill="black")
    
    # Draw white text
    draw.text((x, y), text, font=font, fill="white") 